package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/services/types"
	"xiehui-service/global"
)

type orderDeliveryService struct {
}

type OrderDeliveryResult struct {
	List         []erp_models.OrderDelivery
	TotalPages   int64
	TotalRecords int64
}

var OrderDeliveryService = new(orderDeliveryService)

// 获取单条信息
func (orderDeliveryService *orderDeliveryService) GetOneInfo(id uint) (orderDelivery *erp_models.OrderDelivery, err error) {
	err = global.App.DB.First(&orderDelivery, id).Error
	if err != nil {
		orderDelivery = nil
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

func (orderDeliveryService *orderDeliveryService) GetByUnioNo(unionNo string) (orderDelivery erp_models.OrderDelivery, err error) {
	err = global.App.DB.Where("union_no = ? ", unionNo).Find(&orderDelivery).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 新增
func (orderDeliveryService *orderDeliveryService) Create(orderDelivery erp_models.OrderDelivery) (uint, error) {
	result := global.App.DB.Create(&orderDelivery)
	if result.Error != nil {
		return 0, result.Error
	}
	return orderDelivery.ID.ID, nil
}

func (orderDeliveryService *orderDeliveryService) Update(orderDelivery erp_models.OrderDelivery) (err error) {
	if err := global.App.DB.Model(&erp_models.OrderDelivery{}).Where("ID = ?", orderDelivery.ID.ID).Omit("ID", "UnionNo").Updates(&orderDelivery).Error; err != nil {
		return err
	}
	return nil
}

func (orderDeliveryService *orderDeliveryService) OrderListByLasttime(lastTime string, pagination types.Pagination) (result *OrderDeliveryResult, err error) {
	query := global.App.DB.Model(&erp_models.OrderDelivery{})

	query = query.Where("updated_at > ?", lastTime)

	// 获取总记录数
	var totalRecords int64
	if err = query.Count(&totalRecords).Error; err != nil {
		return nil, err
	}

	// 设置分页查询条件
	offset := (pagination.PageNum - 1) * pagination.PageSize
	query = query.Order("ID DESC").Offset(int(offset)).Limit(int(pagination.PageSize))

	// 获取当前页记录数
	var currentDelivery []erp_models.OrderDelivery
	if err = query.Find(&currentDelivery).Error; err != nil {
		return nil, err
	}

	// 计算总页数
	totalPages := (totalRecords + int64(pagination.PageSize) - 1) / int64(pagination.PageSize)

	return &OrderDeliveryResult{
		List:         currentDelivery,
		TotalPages:   totalPages,
		TotalRecords: totalRecords,
	}, nil
}

// 根据ID更新数据
func (orderDeliveryService *orderDeliveryService) SetById(id uint, fields map[string]interface{}) (err error) {
	var orderDelivery erp_models.OrderDelivery
	if err = global.App.DB.First(&orderDelivery, id).Error; err != nil {
		err = errors.New("未查询到发货单信息")
		return
	}

	if err = global.App.DB.Model(&orderDelivery).Updates(fields).Error; err != nil {
		return
	}

	return nil
}
